package com.thread.lianxi;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Running {

	static final int RUNNER_COUNT = 5;

	public static void main(String[] args) {
		CountDownLatch latch = new CountDownLatch(RUNNER_COUNT);
		ExecutorService service = Executors.newFixedThreadPool(RUNNER_COUNT);
		for (int i = 0; i < RUNNER_COUNT; i++) {
			service.execute(new Runner("参赛者" + i,latch));
		}
		
		try {
			System.out.println("等待"+RUNNER_COUNT+"个参赛者完成比赛");
			latch.await();
			System.out.println(RUNNER_COUNT+"个参赛者完成了比赛。可以排名了");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	static class Runner implements Runnable {

		private String name;
		private CountDownLatch latch;

		public Runner(String name,CountDownLatch latch) {
			this.name = name;
			this.latch = latch;
		}

		@Override
		public void run() {
			System.out.println(name + " 开跑了。。。");
			int time = (new Random()).nextInt(5000);
			System.out.println(name + " 跑了" + time + "毫秒。");
			latch.countDown();
		}

	}
}
